package com.goldplusgold.tradedelay.app.my.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.goldplusgold.network.lib.AppCollectedInfoUtil;
import com.goldplusgold.network.lib.exception.ServerException;
import com.goldplusgold.support.lib.base.fragment.BaseFragment;
import com.goldplusgold.support.lib.utils.DeviceNetworkUtil;
import com.goldplusgold.support.lib.widget.AsyncTask;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.tradedelay.app.my.networkservice.MyService;
import com.goldplusgold.tradedelay.app.my.pojo.CodeInfo;
import com.goldplusgold.tradedelay.app.my.account.UserInfo;
import com.goldplusgold.tradedelay.app.base.utils.ActivityUtils;
import com.goldplusgold.support.lib.utils.AppInfoUtils;
import com.goldplusgold.support.lib.utils.FragmentManagerUtil;
import com.goldplusgold.support.lib.utils.NetWorkConstant;
import com.goldplusgold.support.lib.utils.RegexUtils;
import com.goldplusgold.support.lib.widget.TitleView;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by admin on 2017/5/26.
 */

public class ForgotPasswordFragment extends BaseFragment implements Handler.Callback {
    @BindView(R.id.title_view)
    TitleView titleView;
    @BindView(R.id.et_phoneNum)
    EditText etPhoneNum;
    @BindView(R.id.btn_get_vericode)
    TextView btnGetVericode;
    @BindView(R.id.et_vericode)
    EditText etVericode;
    @BindView(R.id.btn_next)
    Button btnNext;
    @BindView(R.id.txt_description)
    TextView txtDescription;
    @BindView(R.id.iv_delete_phone)
    ImageView ivDeletePhone;
    private int curTime;
    private Timer timer;
    private String phoneNum;
    private String codeNum;
    private int mType;
    private String mBtnText;
    private String mDescribtion;
    private String mWechatCode;
    private final int FORGET_PASSWORD = 1;
    private final int WECHAT_CHECK_PHONE = 2;
    public static final int REFRESH_CODE = 3;
    private Handler handler = new Handler(this);

    public static ForgotPasswordFragment newInstance(int type, String describtion, String btnText, String wechatCode) {
        Bundle args = new Bundle();
        ForgotPasswordFragment fragment = new ForgotPasswordFragment();
        args.putString("btnText", btnText);
        args.putString("describtion", describtion);
        args.putInt("type", type);
        args.putString("wechatCode", wechatCode);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mType = getArguments().getInt("type");
            mBtnText = getArguments().getString("btnText");
            mDescribtion = getArguments().getString("describtion");
            mWechatCode = getArguments().getString("wechatCode");
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_forgot_pwd;
    }

    @Override
    protected void initView() {
        super.initView();
        titleView.getTitletextView().setVisibility(View.VISIBLE);
        titleView.getTitletextView().setText("验证手机号");
        titleView.getBackView().setVisibility(View.VISIBLE);
        txtDescription.setText(mDescribtion);
        btnNext.setText(mBtnText);
        btnNext.setEnabled(false);
        etPhoneNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                phoneNum = s.toString();
                if (phoneNum.length() > 0) {
                    ivDeletePhone.setVisibility(View.VISIBLE);
                } else {
                    ivDeletePhone.setVisibility(View.GONE);
                }
                setBtnClickState();
            }
        });
        etVericode.addTextChangedListener(new TextWatcher() {
                                              @Override
                                              public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                                              }

                                              @Override
                                              public void onTextChanged(CharSequence s, int start, int before, int count) {

                                              }

                                              @Override
                                              public void afterTextChanged(Editable s) {
                                                  codeNum = s.toString();
                                                  setBtnClickState();
                                              }
                                          }

        );
    }

    private void setBtnClickState() {
        if (!TextUtils.isEmpty(phoneNum) && !TextUtils.isEmpty(codeNum)) {
            btnNext.setEnabled(true);
        } else {
            btnNext.setEnabled(false);
        }
    }

    @OnClick({R.id.iv_back, R.id.iv_delete_phone, R.id.btn_get_vericode, R.id.btn_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                getActivity().onBackPressed();
                break;
            case R.id.iv_delete_phone:
                etPhoneNum.setText("");
                break;
            case R.id.btn_get_vericode:
                phoneNum = etPhoneNum.getText().toString().trim();
                if (TextUtils.isEmpty(phoneNum)) {
                    showToastMessage(getString(R.string.please_enter_phone_number), Toast.LENGTH_SHORT);
                    return;
                }
                if (!RegexUtils.checkMobile(phoneNum)) {
                    showToastMessage(getString(R.string.wrong_phone_number), Toast.LENGTH_SHORT);
                    return;
                }
                new GetForgotPwdCodeAsyncTask().execute(AsyncTask.TYPE_NET);
                break;
            case R.id.btn_next:
                if (mType == FORGET_PASSWORD) {
                    new ResetPwdCodeAsyncTask().execute(AsyncTask.TYPE_NET);
                } else {
                    String imei = DeviceNetworkUtil.getIMEIWrap(getContext());
                    new WechatAuthAsyncTask(imei).execute(AsyncTask.TYPE_NET);
                }
                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        if (!isAvailableActivity()) {
            return false;
        }
        int type = msg.what;
        switch (type) {
            case REFRESH_CODE:
                codeCountDown();
                break;
            case NetWorkConstant.NETWORK_ERROR_CODE:
                showToastMessage(R.string.network_error, Toast.LENGTH_LONG);
                break;
            case NetWorkConstant.NETWORK_SERVER_ERROR_CODE:
                String errorMessage = (String) msg.obj;
                showToastMessage(errorMessage, Toast.LENGTH_LONG);
                break;
        }
        return true;
    }

    public class GetForgotPwdCodeAsyncTask extends AsyncTask<Void, Void, CodeInfo> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected CodeInfo doInBackground(Void... params) {
            try {
                CodeInfo codeInfo = null;
                if (mType == FORGET_PASSWORD) {
                    codeInfo = MyService.getInstance().getForgotPwdCode(phoneNum);
                } else {
                    codeInfo = MyService.getInstance().getWechatBindCode(phoneNum);
                }
                if (codeInfo != null) {
                    return codeInfo;
                }
            } catch (ServerException e) {
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }
            return null;
        }

        @Override
        protected void onPostExecute(CodeInfo codeInfo) {
            super.onPostExecute(codeInfo);
            dismisLoadingControl();
            if (codeInfo == null) {
                return;
            }
            if (codeInfo.getStatus()) {
                setTimerTask();
                btnGetVericode.setEnabled(false);
            }
        }

    }

    public class ResetPwdCodeAsyncTask extends AsyncTask<Void, Void, CodeInfo> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected CodeInfo doInBackground(Void... params) {
            try {
                CodeInfo codeInfo = MyService.getInstance().checkPwdCode(codeNum, phoneNum);
                if (codeInfo != null) {
                    return codeInfo;
                }
            } catch (ServerException e) {
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }
            return null;
        }

        @Override
        protected void onPostExecute(CodeInfo codeInfo) {
            super.onPostExecute(codeInfo);
            dismisLoadingControl();
            if (codeInfo == null) {
                return;
            }
            if (codeInfo.getStatus()) {
                FragmentManagerUtil.getInstance().openFragment(getActivity(), ResetForgotPasswordFragment.newInstance(phoneNum, codeNum), true);
            }
        }

    }

    private void sendNetworkErrorMessage(int type, String errorMessage) {
        Message message = handler.obtainMessage();
        message.what = type;
        if (!TextUtils.isEmpty(errorMessage)) {
            message.obj = errorMessage;
        }
        handler.sendMessage(message);
    }

    private void setTimerTask() {
        curTime = 60;
        timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {

                Message msg = new Message();
                msg.what = REFRESH_CODE;
                handler.sendMessage(msg);
                curTime--;
            }
        }, 0, 1000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    private void codeCountDown() {
        if (btnGetVericode == null) {
            return;
        }
        if (curTime == 0) {
            timer.cancel();
            btnGetVericode.setText(R.string.get_vericode_again);
            btnGetVericode.setTextColor(getResources().getColor(R.color.title_bg));
            btnGetVericode.setEnabled(true);
        } else {
            btnGetVericode.setText("(" + curTime + "s)" + getString(R.string.repeat_after_sixty_seconds));
            btnGetVericode.setTextColor(getResources().getColor(R.color.title_bg));
        }
    }

    public class WechatAuthAsyncTask extends AsyncTask<Void, Void, UserInfo> {
        String imei;

        public WechatAuthAsyncTask(String imei) {
            this.imei = imei;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected UserInfo doInBackground(Void... params) {
            try {

                UserInfo userInfo = MyService.getInstance().wechatAuth("android", mWechatCode, "android", phoneNum, codeNum, imei);
                if (userInfo != null) {
                    return userInfo;
                }
            } catch (ServerException e) {

                sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());

            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }

            return null;
        }

        @Override
        protected void onPostExecute(UserInfo userInfo) {
            super.onPostExecute(userInfo);
            dismisLoadingControl();
            if (userInfo == null) {
                return;
            }
            if (userInfo.getStatus()) {
                String token = userInfo.getToken();
                String time = String.valueOf(System.currentTimeMillis());
                String versionName = AppInfoUtils.getVersionName(getActivity());
                AppCollectedInfoUtil.initAppCollectedInfo(getActivity(), token, time, versionName);
                getActivity().setResult(Activity.RESULT_OK);
                finishActivity();
            } else {
                ActivityUtils.gotoWechatRegister(getActivity(), phoneNum, mWechatCode);
            }

        }

    }

}
